package com.rookie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rookie.entity.Menu;
import com.rookie.entity.Role;
import com.rookie.entity.User;
import com.rookie.entity.UserRole;
import com.rookie.mapper.MenuMapper;
import com.rookie.mapper.UserMapper;
import com.rookie.service.MenuService;
import com.rookie.service.RoleService;
import com.rookie.service.UserRoleService;
import com.rookie.service.UserService;
import com.rookie.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * service实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    MenuMapper menuMapper;

    /**
     * 根据用户名获取用户
     */
    @Override
    public User getUserByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return this.getOne(wrapper);
    }

    /**
     * 根据用户id查询用户角色和菜单操作权限
     */
    @Override
    public String getUserAuthorityInfo(Long userId) {
        StringBuilder authority = new StringBuilder();
        if (redisUtil.hasKey("authority:" + userId))
            authority = new StringBuilder(String.valueOf(redisUtil.get("authority:" + userId)));
        else {
            // 查询角色
            LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
            wrapper.inSql(Role::getId, "SELECT role_id FROM sys_user_role WHERE user_id = " + userId);
            List<Role> roleList = roleService.list(wrapper);
            if (CollectionUtils.isNotEmpty(roleList)) {
                String roleCodes = roleList.stream().map(role -> "ROLE" + role.getCode()).collect(Collectors.joining(","));
                authority.append(roleCodes).append(",");
            }
            // 查询菜单操作权限
            List<Long> menuIds = menuMapper.getMenuIdsByUid(userId);
            if (CollectionUtils.isNotEmpty(menuIds)) {
                List<Menu> menusList = menuService.listByIds(menuIds);
                if (CollectionUtils.isNotEmpty(menusList)) {
                    String perms = menusList.stream().map(Menu::getPerms).collect(Collectors.joining(","));
                    authority.append(perms);
                }
            }
            redisUtil.set("authority:" + userId, authority.toString(), 60 * 60);
        }
        return authority.toString();
    }

    /**
     * 根据用户id清除redis中的权限
     */
    @Override
    public void clearRedisAuthorityByUser(Long userId) {
        redisUtil.del("authority:" + userId);
    }

    /**
     * 根据角色id清除redis中的权限
     */
    @Override
    public void clearRedisAuthorityByRole(Long roleId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getRoleId, roleId);
        List<UserRole> userRoleList = userRoleService.list(wrapper);
        userRoleList.forEach(userRole -> clearRedisAuthorityByUser(userRole.getUserId()));
    }

    /**
     * 根据菜单id清除redis中的权限
     */
    @Override
    public void clearRedisAuthorityByMenu(Long menuId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.inSql(UserRole::getRoleId, "SELECT role_id FROM sys_role_menu WHERE menu_id = " + menuId);
        List<UserRole> userRoleList = userRoleService.list(wrapper);
        userRoleList.forEach(userRole -> clearRedisAuthorityByUser(userRole.getUserId()));
    }

}




